package com.dependencies.springjdbc.dao;

import com.dependencies.springjdbc.model.Student;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @author zhizhou   2024/8/23 09:22
 */
@Repository
public class StudentRepository {
    
    @Resource
    private JdbcTemplate jdbcTemplate;
    
    // 插入用户
    public int addStudent(Student Student) {
        String sql = "INSERT INTO student (name, email, age) VALUES (?, ?, ?)";
        return jdbcTemplate.update(sql, Student.getName(), Student.getEmail(), Student.getAge());
    }
    
    // 查询所有用户
    public List<Student> findAllStudents() {
        String sql = "SELECT * FROM student";
        return jdbcTemplate.query(sql, new StudentRowMapper());
    }
    
    // 根据 ID 查询用户
    public Student findStudentById(Long id) {
        String sql = "SELECT * FROM student WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, new StudentRowMapper());
    }
    
    // 更新用户信息
    public int updateStudent(Student student) {
        String sql = "UPDATE student SET name = ?, email = ?, age = ? WHERE id = ?";
        return jdbcTemplate.update(sql, student.getName(), student.getEmail(), student.getAge(), student.getId());
    }
    
    // 删除用户
    public int deleteStudent(Long id) {
        String sql = "DELETE FROM student WHERE id = ?";
        return jdbcTemplate.update(sql, id);
    }
    
    // 查询用户的 Map 结果
    public Map<String, Object> findStudentAsMap(Long id) {
        String sql = "SELECT * FROM student WHERE id = ?";
        return jdbcTemplate.queryForMap(sql, id);
    }
    
    // 查询用户的列表
    public List<Map<String, Object>> findAllStudentsAsMapList() {
        String sql = "SELECT * FROM student";
        return jdbcTemplate.queryForList(sql);
    }
    
    // 批量插入用户
    public int[] batchAddStudents(List<Object[]> batchArgs) {
        String sql = "INSERT INTO student (name, email, age) VALUES (?, ?, ?)";
        return jdbcTemplate.batchUpdate(sql, batchArgs);
    }
    
    // RowMapper 实现，用于将结果集映射到 Student 对象
    private static class StudentRowMapper implements RowMapper<Student> {
        @Override
        public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
            Student student = new Student();
            student.setId(rs.getLong("id"));
            student.setName(rs.getString("name"));
            student.setEmail(rs.getString("email"));
            student.setAge(rs.getInt("age"));
            return student;
        }
    }
}
